package palmtop.com.palmtop.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;

import net.grandcentrix.tray.AppPreferences;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import palmtop.com.palmtop.thread.NotificationThread;
import palmtop.com.palmtop.util.Config;
import palmtop.com.palmtop.util.NetUtil;

public class NotifyService extends Service implements GeocodeSearch.OnGeocodeSearchListener{

    String latitude = "";
    String longitude = "";
    public AMapLocationClient mLocationClient = null;
    public AMapLocationClientOption mLocationOption = null;
    public static  boolean exit = false;
    Context context ;
    String ssgrid;
    String username;
    String userid;
    long time=System.currentTimeMillis()/1000;
    int count = 1;
    private PowerManager.WakeLock wakeLock = null;


    public NotifyService() {

    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, NotifyService.class.getName());
        wakeLock.acquire();
        context = this;
        AppPreferences appPreferences = new AppPreferences(this);
        userid = appPreferences.getString("userid", "");
        username = appPreferences.getString("name", "");
        ssgrid =appPreferences.getString("ssgrid", "");
        //new NotificationThread(context).start();
        checkVersion();

    }
    Disposable mDisposable;
    public void closeTimer(){
        if (mDisposable != null) {
            mDisposable.dispose();
        }
    }

    @Override
    public void onDestroy() {
        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }
        super.onDestroy();
        closeTimer();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    public void checkVersion(){
        Observable.interval(0,30, TimeUnit.SECONDS)
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(Long value) {
                        Log.e("发起请求","发起");
//                        checkVesionRequest();
                        getGpsInfo();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void addPersonpos() {
        RequestParams params = new RequestParams(Config.SERVER_URL + "personpos/save");
        params.addBodyParameter("userid", userid);//任务内容
        params.addBodyParameter("username", username);//任务地点
        params.addBodyParameter("ssgridid", ssgrid);//具体内容
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sDateFormat.format(new Date());
        params.addBodyParameter("logintime", date);// 添加时间
        params.addBodyParameter("longitude", longitude);
        params.addBodyParameter("latitude", latitude);
        NetUtil.postData(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }
            @Override
            public void onCancelled(CancelledException cex) {
            }
            @Override
            public void onFinished() {
            }
        });
    }

    private void getGpsInfo() {
        mLocationClient = new AMapLocationClient(context);
        mLocationClient.setLocationListener(mLocationListener);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setNeedAddress(true);
        mLocationOption.setOnceLocation(true);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();
    }

    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    latitude = amapLocation.getLatitude() + "";
                    longitude = amapLocation.getLongitude() + "";
                    addPersonpos();
                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }

        }
    };

    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {

    }
    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
    }
}
